<template>
  <div class="list-pages white-bg">
    <div class="search-form-box">
      <a-form
        :model="formState"
        name="horizontal_login"
        :label-col="labelCol"
        autocomplete="off"
        @finish="onFinish"
      >
        <a-row :gutter="[16, 16]">
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="学生姓名" name="real_name">
              <a-input
                v-model:value="formState.real_name"
                placeholder="请输入学生姓名"
              >
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="学生账号" name="login_name">
              <a-input
                v-model:value="formState.login_name"
                placeholder="请输入学生账号"
              >
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6" v-show="expand">
            <a-form-item label="账号状态" name="enabled">
              <a-select
                v-model:value="formState.enabled"
                placeholder="请选择账号状态"
              >
                <a-select-option :value="false">禁用</a-select-option>
                <a-select-option :value="true">启用</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-show="expand">
            <a-form-item label="日期" name="dateRange">
              <a-range-picker  v-model:value="formState.dateRange" />
            </a-form-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="12" :lg="6" :xl="6">
            <a-form-item>
              <div class="search-btn-box" :class="{ pt: expand }">
                <a-button
                  :icon="h(SearchOutlined)"
                  type="primary"
                  html-type="submit"
                  class="search-btn"
                  >查询</a-button
                >
                <a-button
                  :icon="h(ReloadOutlined)"
                  class="reset-btn"
                  @click="resetForm"
                  >重置</a-button
                >
                <a
                  class="expand-btn"
                  style="font-size: 12px; margin-left: 12px"
                  @click="expand = !expand"
                >
                  <template v-if="expand">
                    <UpOutlined />
                  </template>
                  <template v-else>
                    <DownOutlined />
                  </template>
                  {{ expand ? "收起查询" : "展开查询" }}
                </a>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="opt-button-box">
      <!-- <a-button type="primary" class="btn" @click="handleAdd">
        <img src="/icons/common/icon-add.png" class="icon" />新增学生</a-button
      >
      <a-button class="btn">
        <img src="/icons/common/icon-import.png" class="icon" />
        批量导入</a-button
      > -->
      <a-button class="btn"
      @click="handleExport"
        ><img
          src="/icons/common/icon-export.png"
          class="icon"
        />批量导出</a-button
      >
    </div>
    <div class="table-wrapper" ref="tableRef">
      <a-table
        class="table-box"
        row-key="index"
        :columns="columns"
        :dataSource="tableData"
        :row-class-name="
          (_record, index) => (index % 2 === 1 ? 'table-striped' : null)
        "
        sticky
        :scroll="{ y: true, x: 1100 }"
        :pagination="pagination"
        @change="onChange"
      >
        <template #bodyCell="{ column, record }">
           <template v-if="column.dataIndex == 'class'">
            {{ record?.joined_class_name_list.join(',')}}
          </template>
          <template v-if="column.dataIndex == 'enabled'">
            {{ record.enabled ? "启用" : "禁用" }}
          </template>
          <template v-if="column.dataIndex == 'login_password'">
            {{ "***" }}
          </template>
          <template v-if="column.dataIndex == 'operation'">
            <a-button type="link" class="link" @click="handleDetail(record)">
              查看
            </a-button>
            <!-- <a-button type="link" class="link" @click="handleEdit(record)">
              编辑
            </a-button> -->
            <a-button type="link" class="link" @click="handleEnabled(record)">
              {{ record.enabled ? "禁用" : "启用" }}
            </a-button>
            <a-button type="link" class="link" @click="handleDelte(record)">
              删除
            </a-button>
            <a-button type="link" class="link" @click="handleReset(record)">
              重置密码
            </a-button>
          </template>
        </template>
      </a-table>
    </div>
    <a-modal
      v-model:open="modal2Visible"
      title="新建学生账号"
      centered
      @ok="modal2Visible = false"
    >
      <a-form
        :model="formState"
        name="horizontal_login"
        layout="vertical"
        :label-col="labelCol"
        autocomplete="off"
        @finish="onFinish"
        :rules="rules"
      >
        <a-row :gutter="[16, 16]">
          <a-col :span="12">
            <a-form-item label="学生姓名" name="keyword1">
              <a-input
                v-model:value="formState.keyword"
                placeholder="请输入学生姓名"
              >
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="账号" name="keyword2">
              <a-input
                v-model:value="formState.keyword"
                placeholder="请输入学生账号"
              >
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="初始密码" name="customer_status_id">
              <a-input
                v-model:value="formState.keyword"
                placeholder="请输入初始密码"
              >
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
    <a-modal
      v-model:open="enabledOpen"
      :title="datas.enabled ? '禁用' : '启用'"
      @ok="handleAPIEnabled"
    >
      <div class="option-dialog">
        <div class="title">
          确定要{{ datas.enabled ? "禁用" : "启用" }}该账号吗？
        </div>
        <div class="content">
          <div class="item">姓名：{{ datas.real_name }}</div>
          <div class="item">账号：{{ datas.login_name }}</div>
        </div>
      </div>
    </a-modal>
    <a-modal v-model:open="resetOpen" title="重置密码" @ok="handleAPIRest">
      <div class="option-dialog">
        <div class="title">确定要重置该账号的密码为“123456”</div>
        <div class="content">
          <div class="item">姓名：{{ datas.real_name }}</div>
          <div class="item">账号：{{ datas.login_name }}</div>
        </div>
      </div>
    </a-modal>
    <a-modal v-model:open="deleteOpen" title="删除" @ok="handleAPIDelete">
      <div class="option-dialog">
        <div class="title">确定要删除该账号吗？该操作不可逆，请谨慎</div>
        <div class="content">
          <div class="item">姓名：{{ datas.real_name }}</div>
          <div class="item">账号：{{ datas.login_name }}</div>
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script setup>
import { ref, computed, h, onMounted, onUnmounted } from "vue";
import {
  SearchOutlined,
  ReloadOutlined,
  DownOutlined,
  UpOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";
import { useGlobalStore } from "@/store/modules/global";
import api from "@/api";
const store = useGlobalStore();
const router = useRouter();
const labelCol = { style: { width: "80px" } };
const rules = ref({
  keyword1: [
    {
      required: true,
      message: "请输入学生姓名",
      trigger: "blur",
    },
  ],
  keyword2: [
    {
      required: true,
      message: "请输入账号",
      trigger: "blur",
    },
  ],
});
const formState = ref({
  real_name: "",
  login_name: "",
  enabled: null,
  dateRange: [],
});
const resetForm = () => {
  formState.value = {
    real_name: "",
    login_name: "",
    enabled: null,
    dateRange: [],
  };
  getData();
};
//tree结构中获取省市名称

const windowWidth = ref(window.innerWidth);
const expand = ref(true);
onMounted(async () => {
  windowWidth.value = window.innerWidth;
  if (windowWidth.value > 768) {
    expand.value = true;
  } else {
    expand.value = false;
  }
  window.addEventListener("resize", () => {
    windowWidth.value = window.innerWidth;
    if (windowWidth.value > 768) {
      expand.value = true;
    } else {
      expand.value = false;
    }
  });
  await getData();
});
onUnmounted(() => {
  window.removeEventListener("resize", () => {});
});

function onFinish(values) {
  console.log("Success:", values);
  getData();
}
const tableData = ref([]);

const columns = ref([
  {
    dataIndex: "student_real_name",
    title: "学生姓名",
    width: 240,
  },
  {
    dataIndex: "login_name",
    title: "学生账号",
    ellipsis: true,
    width: 110,
  },
  {
    dataIndex: "created",
    title: "开通时间",
    width: 200,
  },
   {
    dataIndex: "class",
    title: "所在班级",
    width: 110,
  },
  {
    dataIndex: "student_source_name",
    title: "开通方式",
    width: 150,
  },
  {
    dataIndex: "invite_teach_user_real_name",
    title: "邀请教师",
    width: 110,
  },
  {
    dataIndex: "enabled",
    title: "账号状态",
    width: 150,
  },
  {
    dataIndex: "login_password",
    title: "密码",
    width: 110,
  },
  {
    dataIndex: "operation",
    title: "操作",
    width: 220,
    align: "center",
    fixed: "right",
  },
]);

const onChange = (page) => {
  console.log(page);
  current.value = page.current;
  pageSize.value = page.pageSize;
  getData();
};

const current = ref(1);
const pageSize = ref(10);
const total = ref(0);
const pagination = computed(() => ({
  position: ["bottomCenter"],
  total: total.value,
  current: current.value,
  pageSize: pageSize.value,
  showSizeChanger: true,
  size: "large",
  showTotal: (total) => `共 ${total} 条`,
}));
// 表格数据获取方法
const getData = async () => {
  let params = {
    current: current.value,
    pageSize: pageSize.value,
    real_name: formState.value.real_name || "",
    login_name: formState.value.login_name || "",
    user_enabled: formState.value.enabled,
      created_dateRange: formState.value.dateRange || [],
    for_school_manager:true
  };
  const res = await api.apiStudentPagedListPost({
    args: params,
  });
  tableData.value = res.data.data.map(item=>{
    return {
      ...item,
      ...item.user
    }
  });
  total.value = res.data.total;
};

const modal2Visible = ref(false);
const handleAdd = () => {
  store.setSubTitle("新增学生");
  modal2Visible.value = true;
  // router.push("teacher-account-management-edit");
};

const handleDetail = (data) => {
  store.setSubTitle("查看详情");
  router.push(`student-account-management-detail?id=${data.student_id}`);
};
const handleEdit = (data) => {
  // console.log("编辑学生", data);
  // store.setSubTitle("编辑学生");
  // router.push(`teacher-account-management-edit?id=${data.customer_id}`);
};
const datas = ref({});
const deleteOpen = ref(false);
const handleDelte = (data) => {
  datas.value = data;
  deleteOpen.value = true;
};

const handleAPIDelete = async () => {
  const res = await api.apiStudentDeletePost({ student_id: datas.value.student_id });
  deleteOpen.value = false;
  if (res) {
    message.success("删除成功");
    await getData();
  } else {
    message.error("删除失败");
  }
};
//禁用
const enabledOpen = ref(false);
const handleEnabled = (data) => {
  datas.value = data.user;
  enabledOpen.value = true;
};
const handleAPIEnabled = async () => {
  let params = {
    ...datas.value.user,
    enabled: !datas.value.enabled,
  };
  const res = await api.apiUserUpdatePost(params);
  enabledOpen.value = false;
  if (res.data) {
    message.success("操作成功");
    await getData();
  } else {
    message.error("操作失败");
  }
};
//重置密码
const resetOpen = ref(false);
const handleReset = (data) => {
  datas.value = data.user;
  resetOpen.value = true;
};
const handleAPIRest = async () => {
  let params = {
    ...datas.value,
    login_password: "123456",
  };
  const res = await api.apiUserUpdatePost(params);
  resetOpen.value = false;
  if (res.data) {
    message.success("重置密码成功，新密码为123456");
    await getData();
  } else {
    message.error("重置密码失败");
  }
};

// 导出功能
const handleExport = async () => {
  try {
    // 构建导出参数，使用当前搜索条件
    const exportParams = {
      current: current.value,
      pageSize: pageSize.value,
      real_name: formState.value.real_name || "",
      login_name: formState.value.login_name || "",
      user_enabled: formState.value.enabled,
      created_dateRange: formState.value.dateRange || [],
      for_school_manager:true
    };

    // // 只有当字段有值时才添加到参数中
    // if (formState.value.keyword) {
    //   exportParams.keyword = formState.value.keyword;
    // }
    // if (
    //   formState.value.dealer_id !== undefined &&
    //   formState.value.dealer_id !== null
    // ) {
    //   exportParams.dealer_idArray = [formState.value.dealer_id];
    // }
    // if (
    //   formState.value.customer_status_id !== undefined &&
    //   formState.value.customer_status_id !== null
    // ) {
    //   exportParams.customer_status_idArray = [
    //     formState.value.customer_status_id,
    //   ];
    // }
    // if (
    //   formState.value.city_id !== undefined &&
    //   formState.value.city_id !== null
    // ) {
    //   exportParams.city_idArray = formState.value.city_id;
    // }
    // if (
    //   formState.value.customer_type_id !== undefined &&
    //   formState.value.customer_type_id !== null
    // ) {
    //   exportParams.customer_type_idArray = [formState.value.customer_type_id];
    // }

    console.log("导出参数:", exportParams);
    // 调用导出API
    const response = await api.apiStudentExportPost(exportParams);

    console.log("导出响应:", response);

    if (response.data && response.data.file) {
      const fileData = response.data.file;

      // 
      const base64Content = fileData.fileContents;
      const contentType =
        fileData.contentType ||
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const fileName = fileData.fileDownloadName || "学生列表_导出.xlsx";

      try {
        // 将Base64字符串转换为二进制数据
        const binaryString = atob(base64Content);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }

        // 创建Blob对象
        const blob = new Blob([bytes], { type: contentType });

        // 创建下载链接
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = fileName;

        // 触发下载
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        // 清理URL对象
        window.URL.revokeObjectURL(url);

        message.success("导出成功");
      } catch (decodeError) {
        console.error("文件解码失败:", decodeError);
        message.error("文件解码失败，请稍后重试");
      }
    } else {
      const errorMessage = response?.errors?.[0] || "导出失败";
      console.error("导出失败:", response);
      message.error(errorMessage);
    }
  } catch (error) {
    console.error("导出学生列表失败:", error);
    message.error("导出失败，请稍后重试");
  } finally {
  }
};
</script>
<style lang="less" scoped>
.list-pages {
  height: 100%;
  padding: 0 16px;
  display: flex;
  flex-direction: column;
  .search-box {
    display: flex;
    align-items: center;
    padding: 18px 0;
    flex-wrap: wrap;
    border-bottom: 1px solid #e5e7eb;
    .search-select {
      width: 120px;
    }
    .line {
      width: 1px;
      height: 16px;
      margin: 0 12px;
      background: #bec4ca;
      @media screen and (max-width: 768px) {
        display: none;
      }
    }
    .search-input-box {
      flex: 1;
      display: flex;
      align-items: center;
      @media screen and (max-width: 768px) {
        width: 100%;
        margin-top: 16px;
        justify-content: space-between;
      }
    }
    .search-input {
      flex: 1;
    }
    .search-btn {
      width: 60px;
      height: 32px;
      background: #2776ff;
      border-radius: 4px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
      text-align: center;
      line-height: 32px;
    }
  }
  .table-wrapper {
    width: 100%;
    flex: 1;
    overflow: hidden;
    .table-box {
      height: 100%;
    }
  }
  .list-box {
    width: 100%;
    box-sizing: border-box;
    padding-top: 16px;
    overflow: auto;
    display: grid;
    gap: 16px;
    margin: 0 auto;
    grid-template-columns: repeat(auto-fill, minmax(261px, 1fr));
    justify-content: space-between;
    .list-item {
      width: 261px;
      background: #ffffff;
      border: 1px solid #e6ebf1;
      border-radius: 8px;
      box-sizing: border-box;
      padding: 8px;
      margin: auto;
      position: relative;
      cursor: pointer;
      &:hover {
        border: 1px solid #2776ff;
        box-shadow: 12px 12px 12px 0px rgba(39, 118, 255, 0.1);
      }
      .item-collect {
        position: absolute;
        top: 0;
        right: 0;
        cursor: pointer;
        width: 32px;
        height: 32px;
        background: rgba(0, 0, 0, 0.4) url(@/assets/icon-collet.png) no-repeat
          center center;
        border-radius: 0 8px 0 12px;
        &.cur {
          background: #ffffff url(@/assets/icon-collet-cur.png) no-repeat center
            center;
          border-radius: 0 8px 0 12px;
        }
      }

      .list-img {
        width: 245px;
        height: 249px;
        background: #f3f3f3;
        border: 1px solid #e6ebf1;
        border-radius: 8px;
        box-sizing: border-box;
        img {
          width: 100%;
          height: 100%;
          border-radius: 8px;
        }
      }
      .list-content {
        padding: 14px 0 6px;
        display: flex;
        flex-direction: column;
        .content-title {
          font-family: PingFangSC-Medium;
          font-weight: 500;
          font-size: 16px;
          color: #31323a;
          margin-bottom: 10px;
          line-height: 24px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .content-col {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .col-user {
            display: flex;
            align-items: center;
            .user-img {
              width: 26px;
              height: 26px;
              border-radius: 50%;
            }
            .user-name {
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 12px;
              color: #262626;
              line-height: 16px;
              text-align: left;
              font-style: normal;
            }
          }
          .col-date {
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 12px;
            color: #8c8c8c;
            line-height: 16px;
            text-align: center;
            font-style: normal;
          }
        }
      }
    }
  }

  .pagination-box {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
